package hzh;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBUtils {
    private static String DB_DRIVER = "com.mysql.cj.jdbc.Driver";
    private static String DB_URL    = "jdbc:mysql://127.0.0.1:3306/MyDB";
    private static String DB_USER   = "root";
    private static String DB_PASS   = "5201314huang";

    public static void insert(String sql) throws SQLException {
        excute(sql);
    }

    public static void delete(String sql) throws SQLException {
        excute(sql);
    }

    public static void update(String sql) throws SQLException {
        excute(sql);
    }

    private static void excute(String sql) throws SQLException {
        try {
            Class.forName(DB_DRIVER);//根据字符串的内容按照指定路径找到需要创建的类
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS)) {
            //获取数据库连接
            try (Statement statement = connection.createStatement()) {
                //创建一个statement对象，
                // Statement 是 Java 执行数据库操作的一个重要接口，用于在已经建立数据库连接的基础上，向数据库发送要执行的SQL语句。
                // Statement对象，用于执行不带参数的简单SQL语句。
                statement.execute(sql);//执行sql语句
            }
        }
    }

    public static List<Movies> getMovies(String sql) throws SQLException {//输出数据库中的内容
        try {
            Class.forName(DB_DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        List<Movies> movies = new ArrayList<Movies>();
        try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS)) {
            try (Statement statement = connection.createStatement()) {
                ResultSet rs = statement.executeQuery(sql);//statement.executeQuery将查询结果放置在resultset类中
                while (rs.next()) {
                    Movies movie = new Movies();
                    movie.setId(rs.getInt("id"));
                    movie.setName(rs.getString("name"));
                    movie.setActors(rs.getString("actors"));
                    movie.setType(rs.getString("type"));
                    movie.setScore(rs.getInt("score"));
                    movie.setPrice(rs.getInt("price"));
                    movie.setDescribe(rs.getString("des"));
                    movies.add(movie);
                }
            }
        }

        return movies;
    }
}
